<template>
  <div class="photo-work-detail min-h-screen bg-gray-50 dark:bg-gray-900">
    <!-- 页面头部 -->
    <div class="page-header bg-white dark:bg-gray-800 shadow-sm">
      <div class="container mx-auto px-4 py-6" v-loading="loading">
        <div class="flex flex-col space-y-4">
          <!-- 面包屑导航 -->
          <el-breadcrumb separator="/" class="text-sm">
            <el-breadcrumb-item :to="{ path: '/photography' }"
              >摄影打卡</el-breadcrumb-item
            >
            <el-breadcrumb-item
              :to="{ path: `/photography/${workDetail.spotId}` }"
              >{{ workDetail.spotName }}</el-breadcrumb-item
            >
            <el-breadcrumb-item>作品详情</el-breadcrumb-item>
          </el-breadcrumb>

          <!-- 标题和操作按钮 -->
          <div class="flex items-center justify-between">
            <h1
              class="text-2xl font-bold text-gray-900 dark:text-white line-clamp-1 flex-1 mr-4"
            >
              {{ workDetail.author?.name || '摄影师' }}的摄影作品
            </h1>
            <div class="flex items-center gap-3">
              <el-button-group>
                <el-button
                  type="primary"
                  plain
                  :icon="Share"
                  @click="handleShare"
                  >分享</el-button
                >
                <el-button
                  :type="workDetail.isLiked ? 'primary' : 'default'"
                  plain
                  :icon="Star"
                  @click="handleLike"
                >
                  {{ workDetail.likes }}
                </el-button>
              </el-button-group>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区 -->
    <div class="container mx-auto px-4 py-8">
      <div class="flex flex-col lg:flex-row gap-8">
        <!-- 左侧主要内容区 -->
        <div class="flex-1">
          <!-- 作品展示区 -->
          <div
            class="bg-white dark:bg-gray-800 rounded-lg shadow-sm overflow-hidden"
          >
            <!-- 作品图片 -->
            <div class="p-6">
              <div class="max-w-4xl mx-auto">
                <el-image
                  :src="workDetail.imageUrl"
                  fit="contain"
                  class="w-full rounded-lg shadow-lg"
                  :preview-src-list="[workDetail.imageUrl]"
                />
              </div>
            </div>

            <!-- 作者信息 -->
            <div class="border-t border-gray-100 dark:border-gray-700 p-6">
              <div class="flex items-center justify-between">
                <div
                  class="flex items-center cursor-pointer"
                  @click="$router.push(`/user/profile/${workDetail.author?.id}`)"
                >
                  <el-avatar
                    :size="48"
                    :src="workDetail.author?.avatar"
                    class="mr-3 ring-2 ring-primary-100 dark:ring-primary-900"
                  />
                  <div>
                    <h3
                      class="text-lg font-medium text-gray-900 dark:text-white"
                    >
                      {{ workDetail.author?.name || '摄影师' }}
                    </h3>
                    <p class="text-sm text-gray-500 dark:text-gray-400">
                      {{ formatTime(workDetail.createTime) }}
                    </p>
                  </div>
                </div>
                <el-button type="primary" plain>关注作者</el-button>
              </div>
            </div>

            <!-- 作品描述 -->
            <div class="border-t border-gray-100 dark:border-gray-700 p-6">
              <h4
                class="text-lg font-medium text-gray-900 dark:text-white mb-4"
              >
                作品描述
              </h4>
              <p
                class="text-gray-600 dark:text-gray-400 leading-relaxed whitespace-pre-wrap"
              >
                {{ workDetail.description }}
              </p>
            </div>

            <!-- 拍摄信息 -->
            <div class="border-t border-gray-100 dark:border-gray-700 p-6">
              <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div class="bg-gray-50 dark:bg-gray-700/50 rounded-lg p-4">
                  <h4
                    class="text-lg font-medium text-gray-900 dark:text-white mb-4 flex items-center"
                  >
                    <el-icon class="mr-2"><Camera /></el-icon>
                    拍摄信息
                  </h4>
                  <ul class="space-y-3 text-gray-600 dark:text-gray-400">
                    <li class="flex items-center">
                      <span class="w-20 text-gray-500 dark:text-gray-400"
                        >拍摄时间：</span
                      >
                      <span>{{ workDetail.shootingInfo?.time || '未知' }}</span>
                    </li>
                    <li class="flex items-center">
                      <span class="w-20 text-gray-500 dark:text-gray-400"
                        >相机：</span
                      >
                      <span>{{ workDetail.shootingInfo?.camera || '未知' }}</span>
                    </li>
                    <li class="flex items-center">
                      <span class="w-20 text-gray-500 dark:text-gray-400"
                        >镜头：</span
                      >
                      <span>{{ workDetail.shootingInfo?.lens || '未知' }}</span>
                    </li>
                    <li class="flex items-center">
                      <span class="w-20 text-gray-500 dark:text-gray-400"
                        >参数：</span
                      >
                      <span>{{ workDetail.shootingInfo?.settings || '未知' }}</span>
                    </li>
                  </ul>
                </div>

                <div class="bg-gray-50 dark:bg-gray-700/50 rounded-lg p-4">
                  <h4
                    class="text-lg font-medium text-gray-900 dark:text-white mb-4 flex items-center"
                  >
                    <el-icon class="mr-2"><Location /></el-icon>
                    拍摄地点
                  </h4>
                  <div class="flex items-center justify-between">
                    <div class="text-gray-600 dark:text-gray-400">
                      {{ workDetail.location }}
                    </div>
                    <el-button
                      type="primary"
                      link
                      @click="$router.push(`/photography/${workDetail.spotId}`)"
                    >
                      查看打卡地
                    </el-button>
                  </div>
                </div>
              </div>
            </div>

            <!-- 评论区 -->
            <div class="border-t border-gray-100 dark:border-gray-700 p-6">
              <h4
                class="text-lg font-medium text-gray-900 dark:text-white mb-6 flex items-center"
              >
                <el-icon class="mr-2"><ChatDotRound /></el-icon>
                评论 ({{ workDetail.comments?.length || 0 }})
              </h4>

              <!-- 评论列表 -->
              <div class="space-y-6">
                <div
                  v-for="comment in workDetail.comments || []"
                  :key="comment.id"
                  class="flex gap-4"
                >
                  <el-avatar :size="40" :src="comment.user.avatar" />
                  <div class="flex-1">
                    <div class="flex items-center justify-between mb-2">
                      <div>
                        <span
                          class="font-medium text-gray-900 dark:text-white mr-2"
                        >
                          {{ comment.user.name }}
                        </span>
                        <span class="text-sm text-gray-500 dark:text-gray-400">
                          {{ formatTime(comment.time) }}
                        </span>
                      </div>
                      <el-button
                        type="primary"
                        link
                        size="small"
                        @click="handleReply(comment)"
                      >
                        回复
                      </el-button>
                    </div>
                    <p class="text-gray-600 dark:text-gray-400">
                      {{ comment.content }}
                    </p>
                  </div>
                </div>
              </div>

              <!-- 评论输入框 -->
              <div class="mt-6">
                <el-input
                  v-model="commentContent"
                  type="textarea"
                  :rows="3"
                  placeholder="写下你的评论..."
                  resize="none"
                  class="mb-3"
                />
                <div class="flex justify-end">
                  <el-button type="primary" @click="submitComment">
                    发表评论
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧边栏 -->
        <div class="sidebar lg:w-80 flex-shrink-0">
          <!-- 作者名片 -->
          <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6 mb-6">
            <div class="flex items-center mb-4">
              <div
                @click="$router.push(`/user/profile/${workDetail.author?.id}`)"
              >
                <el-avatar
                  :size="64"
                  :src="workDetail.author?.avatar"
                  class="ring-2 ring-primary-100 dark:ring-primary-900 cursor-pointer"
                  @click.stop="$router.push(`/user/profile/${workDetail.author?.id}`)"
                />
                <div
                  class="ml-4 cursor-pointer"
                  @click.stop="$router.push(`/user/profile/${workDetail.author?.id}`)"
                >
                  <h3 class="font-bold text-lg text-gray-900 dark:text-white">
                    {{ workDetail.author?.name || '摄影师' }}
                  </h3>
                  <p class="text-gray-500 dark:text-gray-400">
                    {{ workDetail.author?.signature || "这个人很懒，什么都没写~" }}
                  </p>
                </div>
              </div>
            </div>
            <div class="stats grid grid-cols-3 gap-4 text-center mb-4">
              <div
                class="stat-item cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700/50 p-2 rounded-lg transition-colors"
              >
                <div class="text-lg font-bold text-gray-900 dark:text-white">
                  {{ workDetail.author?.worksCount || 0 }}
                </div>
                <div class="text-gray-500 dark:text-gray-400">作品</div>
              </div>
              <div
                class="stat-item cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700/50 p-2 rounded-lg transition-colors"
              >
                <div class="text-lg font-bold text-gray-900 dark:text-white">
                  {{ workDetail.author?.followingCount || 0 }}
                </div>
                <div class="text-gray-500 dark:text-gray-400">关注</div>
              </div>
              <div
                class="stat-item cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700/50 p-2 rounded-lg transition-colors"
              >
                <div class="text-lg font-bold text-gray-900 dark:text-white">
                  {{ workDetail.author?.followersCount || 0 }}
                </div>
                <div class="text-gray-500 dark:text-gray-400">粉丝</div>
              </div>
            </div>
            <el-button
              type="primary"
              class="w-full"
              @click="handleFollowAuthor"
            >
              {{ workDetail.author?.isFollowing ? "已关注" : "+ 关注" }}
            </el-button>
          </div>

          <!-- 相关推荐 -->
          <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6">
            <h3
              class="text-lg font-medium text-gray-900 dark:text-white mb-4 flex items-center"
            >
              <el-icon class="mr-2"><Star /></el-icon>
              相关推荐
            </h3>
            <div class="space-y-4">
              <div
                v-for="work in recommendedWorks"
                :key="work.id"
                class="group cursor-pointer"
                @click="$router.push(`/photography/works/${work.id}`)"
              >
                <el-image
                  :src="work.imageUrl"
                  class="w-full aspect-video object-cover rounded-lg mb-2"
                />
                <div class="flex items-center justify-between text-sm">
                  <span
                    class="text-gray-900 dark:text-white group-hover:text-primary-600 dark:group-hover:text-primary-400 transition-colors"
                  >
                    {{ work.title }}
                  </span>
                  <span class="text-gray-500 dark:text-gray-400">
                    {{ formatNumber(work.likes) }}赞
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import {
  Share,
  Star,
  Camera,
  Location,
  ChatDotRound,
  PictureFilled,
} from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import "dayjs/locale/zh-cn";
import service from "@/api/axios";

// 配置dayjs
dayjs.extend(relativeTime);
dayjs.locale("zh-cn");

const router = useRouter();
const route = useRoute();
const commentContent = ref("");
const loading = ref(false);
const workId = ref(route.params.id);

// 测试作品详情
const testWorkDetail = {
  id: route.params.id,
  imageUrl: "https://images.pexels.com/photos/2583852/pexels-photo-2583852.jpeg",
  spotId: 1,
  spotName: "贵港江滨公园",
  author: {
    id: 1,
    name: "摄影师小王",
    avatar: "https://xsgames.co/randomusers/assets/avatars/male/32.jpg",
    isFollowing: false,
  },
  title: "晨曦中的贵港市郁江风光",
  description:
    "这张照片拍摄于贵港市郁江畔的清晨，金色的阳光洒在江面上，远处的城市建筑若隐若现，展现了贵港市独特的城市与自然交融的魅力。",
  camera: "Canon EOS R5",
  lens: "RF 24-70mm f/2.8L IS USM",
  settings: "ISO 100, f/8, 1/125s",
  time: "2023-05-15 06:30:00",
  likes: 256,
  views: 1024,
  isLiked: false,
  comments: [
    {
      id: 1,
      user: {
        id: 2,
        name: "风光摄影爱好者",
        avatar: "https://xsgames.co/randomusers/assets/avatars/male/44.jpg",
      },
      content: "构图很好，光线捕捉得恰到好处，真实展现了贵港的晨曦美景！",
      time: "2023-05-15 10:30:00",
    },
    {
      id: 2,
      user: {
        id: 3,
        name: "旅行达人",
        avatar: "https://xsgames.co/randomusers/assets/avatars/female/22.jpg",
      },
      content: "颜色处理很自然，没有过度饱和，保留了清晨的那种宁静感。",
      time: "2023-05-15 11:15:00",
    },
    {
      id: 3,
      user: {
        id: 4,
        name: "摄影学习者",
        avatar: "https://xsgames.co/randomusers/assets/avatars/male/56.jpg",
      },
      content: "请问这是用什么后期软件处理的？色彩非常舒服。",
      time: "2023-05-15 13:20:00",
    },
  ],
};

// 作品详情数据
const workDetail = ref({ ...testWorkDetail });

// 相关推荐列表
const recommendedWorks = ref([]);

// 格式化时间
const formatTime = (time) => {
  return dayjs(time).fromNow();
};

// 格式化数字
const formatNumber = (num) => {
  return new Intl.NumberFormat().format(num);
};

// 获取作品详情
const fetchWorkDetail = async () => {
  loading.value = true;
  try {
    const res = await service.get(`/public/photography/works/${workId.value}`);
    if (res.data) {
      // 确保数据结构与模板匹配
      const data = res.data;
      
      // 处理作者信息
      workDetail.value = {
        id: data.id,
        imageUrl: data.imageUrl,
        spotId: data.spotId,
        spotName: data.spotName,
        author: {
          id: data.userId,
          name: data.nickname || data.username,
          avatar: data.userAvatar,
          isFollowing: false,
          signature: "",
          worksCount: 0,
          followingCount: 0,
          followersCount: 0
        },
        title: data.title,
        description: data.description,
        createTime: data.createdAt,
        likes: data.likes || 0,
        views: data.views || 0,
        isLiked: data.isLiked || false,
        comments: [],
        location: data.spotName,
        // 构建拍摄信息
        shootingInfo: {
          time: data.shootingTime,
          camera: data.camera,
          lens: data.lens,
          settings: data.settings
        }
      };
    }
  } catch (error) {
    console.error('获取作品详情失败:', error);
    // 保留测试数据
  } finally {
    loading.value = false;
  }
};

// 获取相关推荐
const fetchRecommendedWorks = async () => {
  try {
    const res = await service.get(`/public/photography/works/${workId.value}/related`);
    if (res.data) {
      recommendedWorks.value = res.data;
    } else {
      // 使用测试数据
      recommendedWorks.value = Array.from({ length: 3 }, (_, i) => ({
        id: i + 1,
        imageUrl: [
          "https://images.pexels.com/photos/3225517/pexels-photo-3225517.jpeg",
          "https://images.pexels.com/photos/1486974/pexels-photo-1486974.jpeg",
          "https://images.pexels.com/photos/6039251/pexels-photo-6039251.jpeg"
        ][i],
        title: `广西风光作品 ${i + 1}`,
        likes: Math.floor(Math.random() * 500 + 100)
      }));
    }
  } catch (error) {
    console.error('获取相关推荐失败:', error);
    // 使用测试数据
    recommendedWorks.value = Array.from({ length: 3 }, (_, i) => ({
      id: i + 1,
      imageUrl: [
        "https://images.pexels.com/photos/3225517/pexels-photo-3225517.jpeg",
        "https://images.pexels.com/photos/1486974/pexels-photo-1486974.jpeg",
        "https://images.pexels.com/photos/6039251/pexels-photo-6039251.jpeg"
      ][i],
      title: `广西风光作品 ${i + 1}`,
      likes: Math.floor(Math.random() * 500 + 100)
    }));
  }
};

// 获取评论列表
const fetchComments = async () => {
  try {
    const res = await service.get(`/public/photography/works/${workId.value}/comments`);
    if (res.data) {
      workDetail.value.comments = res.data;
    }
  } catch (error) {
    console.error('获取评论列表失败:', error);
    // 保留测试数据的评论
  }
};

// 处理点赞
const handleLike = async () => {
  try {
    const url = `/photography/works/${workId.value}/like`;
    const method = workDetail.value.isLiked ? 'delete' : 'post';
    
    await service[method](url);
    
    workDetail.value.isLiked = !workDetail.value.isLiked;
    workDetail.value.likes += workDetail.value.isLiked ? 1 : -1;
    ElMessage.success(workDetail.value.isLiked ? "点赞成功" : "已取消点赞");
  } catch (error) {
    console.error("点赞失败:", error);
    ElMessage.error("操作失败");
  }
};

// 处理分享
const handleShare = () => {
  ElMessage.success("分享功能开发中");
};

// 处理回复
const handleReply = (comment) => {
  commentContent.value = `@${comment.user.name} `;
};

// 提交评论
const submitComment = async () => {
  if (!commentContent.value.trim()) {
    return ElMessage.warning("请输入评论内容");
  }

  try {
    const data = {
      workId: workId.value,
      content: commentContent.value,
    };
    
    const res = await service.post('/photography/works/comments', data);
    
    // 使用后端返回的评论，或者构造一个新评论
    const newComment = res.data || {
      id: Date.now(),
      user: {
        name: "当前用户",
        avatar: "https://xsgames.co/randomusers/assets/avatars/male/10.jpg",
      },
      content: commentContent.value,
      time: dayjs().format("YYYY-MM-DD HH:mm:ss"),
    };
    
    workDetail.value.comments.unshift(newComment);
    commentContent.value = "";
    ElMessage.success("评论成功");
  } catch (error) {
    console.error("评论失败:", error);
    ElMessage.error("评论失败");
  }
};

// 处理关注作者
const handleFollowAuthor = async () => {
  if (!workDetail.value.author || !workDetail.value.author.id) {
    return ElMessage.warning("作者信息不完整");
  }
  
  try {
    // 使用测试数据，不调用API
    workDetail.value.author.isFollowing = !workDetail.value.author.isFollowing;
    ElMessage.success(
      workDetail.value.author.isFollowing ? "关注成功" : "已取消关注",
    );
  } catch (error) {
    console.error("关注失败:", error);
    ElMessage.error("操作失败");
  }
};

// 页面加载时获取数据
onMounted(() => {
  fetchWorkDetail();
  fetchRecommendedWorks();
  fetchComments();
});
</script>

<style lang="scss" scoped>
.photo-work-detail {
  :deep(.el-breadcrumb) {
    .el-breadcrumb__inner {
      @apply text-gray-500 dark:text-gray-400;
      &.is-link {
        @apply hover:text-primary-600 dark:hover:text-primary-400;
      }
    }
  }

  :deep(.el-button-group) {
    .el-button {
      @apply border-gray-200 dark:border-gray-700;
      &:hover {
        @apply border-primary-600 dark:border-primary-400;
      }
      &.is-active {
        @apply border-primary-600 dark:border-primary-400 bg-primary-600 dark:bg-primary-400 text-white;
      }
    }
  }

  :deep(.el-input__wrapper) {
    @apply bg-transparent dark:bg-gray-700 border-gray-200 dark:border-gray-600;
    box-shadow: none !important;
  }

  :deep(.el-textarea__inner) {
    @apply bg-transparent dark:bg-gray-700 text-gray-900 dark:text-gray-100;
    &::placeholder {
      @apply text-gray-400 dark:text-gray-500;
    }
  }
}
</style>
